package team.nine.kuaichezuche.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.nine.kuaichezuche.model.VehicleInfo;
import team.nine.kuaichezuche.model.VehicleInstance;
import team.nine.kuaichezuche.model.User;
import team.nine.kuaichezuche.repository.UserRepository;
import team.nine.kuaichezuche.service.VehicleClassificationService;
import team.nine.kuaichezuche.service.VehicleInfoService;
import team.nine.kuaichezuche.service.VehicleInstanceService;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 车辆信息分类服务实现类，实现处理前端提交的混合信息并自动分类的业务逻辑
 */
@Service
public class VehicleClassificationServiceImpl implements VehicleClassificationService {

    @Autowired
    private VehicleInfoService vehicleInfoService;

    @Autowired
    private VehicleInstanceService vehicleInstanceService;

    @Autowired
    private UserRepository userRepository;

    // 日期格式化对象
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 处理前端提交的混合车辆信息
     */
    @Override
    public Map<String, Object> processMixedVehicleData(Map<String, Object> mixedVehicleData) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 创建或获取现有的车辆信息对象
            VehicleInfo vehicleInfo = extractAndSaveVehicleInfo(mixedVehicleData);

            // 2. 创建车辆实例对象
            VehicleInstance vehicleInstance = extractAndSaveVehicleInstance(mixedVehicleData, vehicleInfo);

            // 3. 设置处理结果
            result.put("success", true);
            result.put("message", "车辆信息处理成功");
            result.put("vehicleInfoId", vehicleInfo.getId());
            result.put("vehicleInstanceId", vehicleInstance.getId());

        } catch (Exception e) {
            // 处理异常
            result.put("success", false);
            result.put("message", "车辆信息处理失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 从混合数据中提取车辆信息并保存到数据库
     */
    private VehicleInfo extractAndSaveVehicleInfo(Map<String, Object> mixedVehicleData) {
        // 检查是否提供了车辆信息ID
        if (mixedVehicleData.containsKey("vehicleInfoId")) {
            Integer vehicleInfoId = Integer.parseInt(mixedVehicleData.get("vehicleInfoId").toString());
            VehicleInfo existingVehicleInfo = vehicleInfoService.getVehicleInfoById(vehicleInfoId);
            if (existingVehicleInfo != null) {
                return existingVehicleInfo;
            }
        }

        // 检查是否提供了品牌和车型，如果提供了，尝试查找现有记录
        if (mixedVehicleData.containsKey("brand") && mixedVehicleData.containsKey("model")) {
            String brand = mixedVehicleData.get("brand").toString();
            String model = mixedVehicleData.get("model").toString();
            VehicleInfo existingVehicleInfo = findExistingVehicleInfoByBrandAndModel(brand, model);
            if (existingVehicleInfo != null) {
                return existingVehicleInfo;
            }
        }

        // 创建新的车辆信息对象
        VehicleInfo vehicleInfo = new VehicleInfo();

        // 设置车辆信息字段
        if (mixedVehicleData.containsKey("brand")) {
            vehicleInfo.setBrand(mixedVehicleData.get("brand").toString());
        }
        if (mixedVehicleData.containsKey("model")) {
            vehicleInfo.setModel(mixedVehicleData.get("model").toString());
        }
        if (mixedVehicleData.containsKey("color")) {
            vehicleInfo.setColor(mixedVehicleData.get("color").toString());
        }
        if (mixedVehicleData.containsKey("seatCount")) {
            vehicleInfo.setSeatCount(Byte.parseByte(mixedVehicleData.get("seatCount").toString()));
        }
        if (mixedVehicleData.containsKey("powerType")) {
            String powerTypeStr = mixedVehicleData.get("powerType").toString();
            try {
                // 兼容中文/英文、大小写
                VehicleInfo.PowerType powerType;
                try {
                    powerType = VehicleInfo.PowerType.valueOf(powerTypeStr);
                } catch (IllegalArgumentException e) {
                    // 尝试英文字段映射
                    if ("GASOLINE".equalsIgnoreCase(powerTypeStr) || "PETROL".equalsIgnoreCase(powerTypeStr)) powerType = VehicleInfo.PowerType.汽油;
                    else if ("DIESEL".equalsIgnoreCase(powerTypeStr)) powerType = VehicleInfo.PowerType.柴油;
                    else if ("ELECTRIC".equalsIgnoreCase(powerTypeStr)) powerType = VehicleInfo.PowerType.电动;
                    else if ("HYBRID".equalsIgnoreCase(powerTypeStr) || "HYBRID_ELECTRIC".equalsIgnoreCase(powerTypeStr)) powerType = VehicleInfo.PowerType.油电混动;
                    else throw e;
                }
                vehicleInfo.setPowerType(powerType);
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("无效的动力类型: " + powerTypeStr);
            }
        }

        // 保存车辆信息
        return vehicleInfoService.createVehicleInfo(vehicleInfo);
    }

    /**
     * 从混合数据中提取车辆实例信息并保存到数据库
     */
    private VehicleInstance extractAndSaveVehicleInstance(Map<String, Object> mixedVehicleData, VehicleInfo vehicleInfo) throws ParseException {
        VehicleInstance vehicleInstance = new VehicleInstance();

        // 设置车辆实例字段
        if (mixedVehicleData.containsKey("licensePlate")) {
            vehicleInstance.setLicensePlate(mixedVehicleData.get("licensePlate").toString());
        }
        if (mixedVehicleData.containsKey("mileage")) {
            vehicleInstance.setMileage(Integer.parseInt(mixedVehicleData.get("mileage").toString()));
        }
        if (mixedVehicleData.containsKey("rentalCount")) {
            vehicleInstance.setRentalCount(Integer.parseInt(mixedVehicleData.get("rentalCount").toString()));
        }
        if (mixedVehicleData.containsKey("availableStart")) {
            Date availableStart = parseDateFlexible(mixedVehicleData.get("availableStart"));
            vehicleInstance.setAvailableStart(availableStart);
        }
        if (mixedVehicleData.containsKey("availableEnd")) {
            Date availableEnd = parseDateFlexible(mixedVehicleData.get("availableEnd"));
            vehicleInstance.setAvailableEnd(availableEnd);
        }
        if (mixedVehicleData.containsKey("ownerId")) {
            Long ownerId = Long.parseLong(mixedVehicleData.get("ownerId").toString());
            User owner = userRepository.findById(ownerId).orElseThrow(() -> new IllegalArgumentException("车主不存在，ID: " + ownerId));
            vehicleInstance.setOwner(owner);
        }
        vehicleInstance.setVehicleInfo(vehicleInfo);
        if (mixedVehicleData.containsKey("dailyRate")) {
            BigDecimal dailyRate = new BigDecimal(mixedVehicleData.get("dailyRate").toString());
            vehicleInstance.setDailyRate(dailyRate);
        }
        if (mixedVehicleData.containsKey("nextMaintenance")) {
            Date nextMaintenance = parseDateFlexible(mixedVehicleData.get("nextMaintenance"));
            vehicleInstance.setNextMaintenance(nextMaintenance);
        }
        if (mixedVehicleData.containsKey("insuranceInfo")) {
            vehicleInstance.setInsuranceInfo(mixedVehicleData.get("insuranceInfo").toString());
        }
        if (mixedVehicleData.containsKey("status")) {
            vehicleInstance.setStatus(Byte.parseByte(mixedVehicleData.get("status").toString()));
        }

        // 保存车辆实例
        return vehicleInstanceService.createVehicleInstance(vehicleInstance);
    }

    /**
     * 兼容不同来源的日期格式（字符串、时间戳、ISO8601）
     */
    private Date parseDateFlexible(Object source) throws ParseException {
        if (source == null) return null;
        if (source instanceof Date) return (Date) source;
        String s = source.toString();
        // 尝试时间戳（毫秒）
        try {
            if (s.matches("^\\d{10,13}$")) {
                long ts = Long.parseLong(s);
                if (s.length() == 10) ts = ts * 1000;
                return new Date(ts);
            }
        } catch (Exception ignored) {}
        // 尝试 ISO8601
        try {
            if (s.contains("T")) {
                return javax.xml.bind.DatatypeConverter.parseDateTime(s).getTime();
            }
        } catch (Exception ignored) {}
        // 回退到固定格式
        return DATE_FORMAT.parse(s);
    }

    /**
     * 根据品牌和车型查找现有的车辆信息
     */
    private VehicleInfo findExistingVehicleInfoByBrandAndModel(String brand, String model) {
        // 通过 VehicleInfoService 调用 findByBrandAndModel 方法
        List<VehicleInfo> vehicleInfos = vehicleInfoService.getVehicleInfoByBrandAndModel(brand, model);
        if (vehicleInfos != null && !vehicleInfos.isEmpty()) {
            // 返回第一个匹配的车辆信息
            return vehicleInfos.get(0);
        }
        return null;
    }
}